Repository navigation
fix(readiness): serve the published generation during a staged rebuild (#145) - #162
Conversation
…rce (#145) Review follow-up for #162. - The rebuild overlay now applies only while the live owner's target_commit equals the freshly observed HEAD and the tracked tree is clean. A HEAD that moved away from the build's target, or tracked edits, fall back to the fail-closed missing_provenance. serving_stale also requires rebuild.target_commit == current_commit. - An owner whose process start time was not recorded, or cannot be read now, is not provably alive and counts as dead. The start time comes from Linux /proc, falling back to psutil create_time() (a core dependency) on hosts without /proc. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per query (#145) Second review follow-up for #162. - Persistent index writes no longer reach a generation a staged rebuild is about to replace. While readiness carries `rebuild`, write_summaries (including task mode) and summarize_sample(persist=true) return code "rebuild_in_progress" with a retry remediation. Right before writing they recheck RepoResolver.accepts_writes(ctx) (registry fence and file identity, no git), and the same check is the writer's per-batch cancel_check, so a rebuild that starts mid-run stops it at the next batch and the response says what may be lost. Lazy summary enqueue from search_code is skipped during a rebuild. Read-only queries are still served. - A served query now observes `git status` once per checkout: readiness classification reuses a request-scoped snapshot (contextvar, carried into the search executor thread) through admission and context creation, and only the post-query recheck observes git again, fresh. A HEAD move or a newly dirty tree during the query returns index_unavailable. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#145) A staged build set index_publication_pending for its whole run, which readiness reported as missing_provenance, so every update - even a quick incremental - made search_code/symbol_lookup fail closed. The build now records its owner next to the repository writer.lock (.mcp-index/rebuild-owner.json: pid, process start time, host, registration and published generation, target commit) before the fence goes up, and clears it in finally (publish, failure or abort). The owner is alive only while that process exists with the same start time on this host and still holds the writer lock. While the owner is alive, readiness classifies the published generation (ready for a same-commit rebuild, stale_commit while a newer commit is indexed) and adds an additive `rebuild` object. search_code and symbol_lookup serve the published generation; stale responses carry the stale readiness and a note. A dead or unprovable owner keeps missing_provenance and fails closed; every other non-ready state is unchanged, and mutating tools still require ready. The live store's handles are now released after the publish swap rather than before it, so a query admitted during the build finishes on its open connection and is then refused by the existing generation recheck. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rce (#145) Review follow-up for #162. - The rebuild overlay now applies only while the live owner's target_commit equals the freshly observed HEAD and the tracked tree is clean. A HEAD that moved away from the build's target, or tracked edits, fall back to the fail-closed missing_provenance. serving_stale also requires rebuild.target_commit == current_commit. - An owner whose process start time was not recorded, or cannot be read now, is not provably alive and counts as dead. The start time comes from Linux /proc, falling back to psutil create_time() (a core dependency) on hosts without /proc. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per query (#145) Second review follow-up for #162. - Persistent index writes no longer reach a generation a staged rebuild is about to replace. While readiness carries `rebuild`, write_summaries (including task mode) and summarize_sample(persist=true) return code "rebuild_in_progress" with a retry remediation. Right before writing they recheck RepoResolver.accepts_writes(ctx) (registry fence and file identity, no git), and the same check is the writer's per-batch cancel_check, so a rebuild that starts mid-run stops it at the next batch and the response says what may be lost. Lazy summary enqueue from search_code is skipped during a rebuild. Read-only queries are still served. - A served query now observes `git status` once per checkout: readiness classification reuses a request-scoped snapshot (contextvar, carried into the search executor thread) through admission and context creation, and only the post-query recheck observes git again, fresh. A HEAD move or a newly dirty tree during the query returns index_unavailable. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rebuild_in_progress (#145) Third review follow-up for #162. - Summary writes are now checked at the persistence point, after the provider call returns. ChunkWriter takes an optional write_fence, a context manager entered around each batch transaction and each single chunk write. RepoResolver.generation_write_fence takes the repository writer lock without waiting and yields whether the registration and published generation still accept writes, so no staged build can begin between the check and the commit. A fenced batch stores nothing, and SummaryGenerationResult.write_fenced reports it; process_scope stops on it. - write_summaries (direct and task mode) and summarize_sample(persist=true) pass the fence and return rebuild_in_progress, with partial counts, when a write is fenced. Batches committed before the fence are kept, since they precede any rebuild's snapshot. - Lazy summary entries carry the fence of the generation the query read; they are dropped before the provider call when already fenced, and checked again at the write. - A shared rebuild_in_progress branch is added to the write_summaries and summarize_sample output schemas, with jsonschema validation tests. - The query gates fall back to `ready` for duck-typed readiness objects that lack `queryable`/`serving_stale`/`rebuild`. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bbaa44b to
4ae09f8
Compare
…elope for tasks (#145) Fourth review follow-up for #162. - The persistent-write fence now yields a WriteGate instead of a bool. FENCED means a staged rebuild owns the generation (the entry is fenced or replaced, or a live rebuild owner holds the writer lock), so the work is obsolete. BUSY means another writer (a sync, or `mcp-index repository summarize`) holds the lock while no rebuild runs and the generation is unchanged, so the write is retryable. - write_summaries and summarize_sample(persist=true) return a retryable `writer_busy` result with partial counts on BUSY, and keep `rebuild_in_progress` for FENCED. SummaryGenerationResult gains write_busy, and process_scope stops on either. - Lazy entries are dropped only on FENCED. On BUSY they are requeued with exponential backoff (2 s doubling, capped at 60 s), at most five times, with the generation rechecked when they are admitted again; dropping after the last retry is logged. - Task-backed write_summaries builds its refusal with the same shared envelope (summary_write_refusal) as the synchronous tool, keeping the task counters. writer_busy joins rebuild_in_progress in both tools' output schemas, and jsonschema tests cover the direct and task results. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… entries at shutdown (#145) Fifth review follow-up for #162. - ChunkWriter counts the rows it actually stores (committed_writes, incremented only when _persist_summary stores a row), and SummaryGenerationResult gains summaries_committed (in summarize_file_chunks and every process_scope result). summaries_written still counts what a call generated or completed, which can include rows another writer stored during the provider call. - summary_write_refusal takes an explicit `committed` count, which alone decides mutation_performed, the note and `summaries_committed`. write_summaries (direct and task mode) and summarize_sample derive their refusal counters from it, and summarize_sample file entries report summaries_committed. The output schema lists the new field. - LazyChunkWriter.stop() logs one line with the number of pending entries it drops, queued or in flight (including one backing off), without their content. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#145) Sixth review follow-up for #162. - Each summarize_file_chunks call, and each lazy queued entry, opens its own write tally (a ContextVar, isolated per asyncio task). _persist_summary and the write fence record committed, fenced and busy writes into the active call's tally. write_fenced, write_busy and summaries_committed come from that tally, and process_scope sums summaries_committed from its file results. Concurrent calls sharing one writer no longer pick up each other's commits through a delta of the writer's cumulative counters, which remain only as diagnostics. - Successful summarize_sample responses are unchanged again: summaries_committed appears only in refusal envelopes. Refs #145 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nce (#145 re-review) The preflight fence of a queued lazy entry ran before the entry opened its own write tally, so a worker that inherited an active context (or a nested call) recorded the entry's BUSY/FENCED outcome into an unrelated caller's tally. The entry's tally now covers the preflight and every early return. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e460193c29
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| @property | ||
| def queryable(self) -> bool: | ||
| """True when indexed query tools may serve the published generation.""" | ||
| return self.ready or self.serving_stale |
There was a problem hiding this comment.
Preserve the documented non-ready query admission contract
During a newer-commit rebuild, this makes stale_commit queryable and allows indexed results instead of the required native-search fallback. The root AGENTS.md MRREADY rollout contract explicitly requires non-ready query paths to return index_unavailable with safe_fallback: "native_search". Labeling the results stale does not preserve that contract. Keep non-ready admission fail-closed, or explicitly reconcile the repository contract with this new exception before enabling it.
AGENTS.md reference: AGENTS.md:L174-L175
Useful? React with 👍 / 👎.
| if readiness is not None and not readiness_queryable(readiness): | ||
| return _index_unavailable_response(readiness, "symbol_lookup", symbol=symbol) |
There was a problem hiding this comment.
Isolate symbol fallback from staging-generation plugins
When a newer-commit rebuild is running, admitting symbol_lookup also exposes the staging plugins, not just the published SQLite generation. EnhancedDispatcher.lookup() falls back to plugins_for(ctx.repo_id) when the published symbol table misses but BM25 supplies an extension hint; staging uses that same repository-keyed plugin set. For example, if the published JavaScript contains a reference to a name and the rebuild adds its definition, the JavaScript plugin's _symbol_cache can return the newly staged definition and its temporary staging path before publication. The generation recheck still passes because the published generation has not changed. Disable plugin fallback while serving a rebuilding generation, or isolate and select plugins by generation.
Useful? React with 👍 / 👎.
Summary
Every staged build, even a quick incremental update, set
index_publication_pendingon the registry entry for the whole build. Readiness reported that asmissing_provenance, sosearch_codeandsymbol_lookupfailed closed during every update. The published generation is never modified during a staged build, so it can keep serving reads while the build runs.Owner record. Before the read fence goes up, the build records its owner next to the existing
writer.lockin.mcp-index/rebuild-owner.json. The record holds the pid, process start time, host, registration id, published generation, target commit andstarted_at. It is cleared infinally(publish, failure or abort). If it cannot be written, behaviour is the same as before (fail closed).Liveness check. The owner counts as alive only when all of these hold:
/procor otherwise psutilcreate_time();flockprobe.If the start time was not recorded or cannot be read now, the owner counts as dead.
Readiness. The rebuild overlay applies only when the owner is alive, the build's
target_commitequals the HEAD observed now, and the tracked tree is clean. Readiness then classifies against the published generation and adds arebuildobject. In every other case readiness is the same as before this PR.Query gates.
search_codeandsymbol_lookup(MCP andIndexItClient),RepoResolver.resolve_ready/is_currentandStoreRegistry.is_currentacceptqueryable:ready, orstale_commitwhile a live rebuild targets the current commit. Duck-typed readiness objects fall back toready.Summary writes are fenced at the write itself.
ChunkWritertakes an optionalwrite_fence. It is entered around each batch transaction and each single-chunk write, after the provider call returns.RepoResolver.generation_write_fencetakes the repository writer lock without waiting, so no build can begin between the check and the commit. It yields aWriteGate, and unless the gate isALLOWEDthe batch stores nothing:FENCED: a staged rebuild owns the generation (the entry is fenced or replaced, or a live rebuild owner holds the lock). The work is obsolete.SummaryGenerationResult.write_fencedreports it.BUSY: another writer (a sync, ormcp-index repository summarize) holds the lock, no rebuild runs and the generation is unchanged. The write is retryable.write_busyreports it.rebuildis set,write_summaries(direct and task mode) andsummarize_sample(persist=true)returnrebuild_in_progressup front.rebuild_in_progress, with partial counts. A busy write returns a retryablewriter_busywith partial counts.One git observation per served query. A request-scoped readiness snapshot is used for admission and context creation. Only the post-query recheck observes git again, fresh. A HEAD move or a newly dirty tree during the query returns
index_unavailable.Publish swap. The live store's handles are released after
publish_generation. A query admitted during the build finishes on its open connection, and the generation recheck then refuses it.Owner decision (fixed)
Serve from the current published generation during a staged rebuild, reported as stale, and fail closed only if the build's owner has died.
Readiness during a staged build
search_code/symbol_lookupmissing_provenanceready+rebuildrebuild_in_progressmissing_provenancestale_commit+rebuildreadinessand anoteready)missing_provenancemissing_provenanceindex_unavailablemissing_provenancemissing_provenanceindex_unavailablepartial_index_failure)missing_provenancemissing_provenanceindex_unavailablestale_commitwith no rebuild runningstale_commitstale_commitindex_unavailable(unchanged)rebuild_in_progresswith partial counts, or the lazy entry is droppedwriter_busywith partial counts, or the lazy entry is requeued with bounded backoffClient-visible fields (all additive)
readiness.rebuild:{"in_progress": true, "target_commit": "<sha>", "started_at": "<iso>"}, ornull.search_codeis served stale, it returns the envelope{"results", "query", "readiness", "note"}.symbol_lookupresponses carryreadinessand anotewhen served stale.write_summariesandsummarize_samplecan return a shared refusal envelope{"error", "code", "tool", "mutation_performed", "retryable": true, "readiness", "message", "remediation"}, withcodeeitherrebuild_in_progressorwriter_busy, plussummaries_committed. Partial counters (chunks_summarized,summary_chunks_attempted,summary_missing_chunks, orfiles/total_chunks) are included, plus anotewhen some work was committed.summaries_committed, the refusal'schunks_summarized/total_chunks, andmutation_performedcount only rows this request itself stored, not summaries it generated that another writer stored meanwhile. Task-modewrite_summariesreturns the same envelope with the task counters. Both codes are branches in both tools' output schemas.SummaryGenerationResult.to_dict()gainswrite_fenced,write_busyandsummaries_committed. These come from a per-call write tally (a ContextVar, isolated per asyncio task), so concurrent calls sharing one writer never count each other's writes. Successfulsummarize_sampleandwrite_summariesresponses are unchanged;summaries_committedappears only in refusal envelopes.LazyChunkWriter.stop()logs one line with the number of pending lazy entries it drops, queued or in flight. It logs counts only, no content.get_statusrepository rows gainrebuildand, while served stale, showquery_status: "serving_stale".stale_commit. The admin/search/optimizeand/search/rebuildendpoints are unchanged and tracked in a follow-up issue.mcp-index repository summarize(feat(cli): resumablerepository summarizesummary prefill (#121) #157) already holds the writer lock for its whole run and refuses during a rebuild, so it is unchanged.Tests (fakes and
tmp_pathonly;uv run --extra dev pytest <files> -n 2 --no-cov)New file
tests/test_issue_145_serve_during_rebuild.py: 45 tests, all passed. They cover:git statuscalls per served query, and the post-query recheck.Added in the third review round:
summarize_sample(persist=true)where the rebuild begins during the provider await, by fence flag and by another thread holding the writer lock with a live rebuild owner. Nothing is stored in the old generation and the response isrebuild_in_progress. A no-rebuild control proves the same call does persist.search_codeenqueues lazy entries with a generation fence that flips fromALLOWEDtoFENCEDonce a rebuild fences the entry.write_summariesandsummarize_samplerebuild_in_progressresponses validate against the advertised output schemas withjsonschema.Added in the fourth review round (a busy writer vs a rebuild):
summarize_sample(persist=true)is parametrized over no rebuild, the fence flag, a rebuild holding the lock with a live owner, and a busy non-rebuild writer. The rebuild cases giverebuild_in_progress, the busy case giveswriter_busy, nothing is stored in either, and each response validates against the schema.write_summarieswhile a non-rebuild writer holds the lock: retryablewriter_busywith partial counts,readiness.rebuildnull, nothing stored, schema-valid. The retry after the writer finishes persists.write_summarieswith the first batch fenced or busy returns the shared envelope with the task counters, and it validates against thewrite_summariesschema.Added in the fifth review round (committed vs generated):
write_summariesover two files, where another writer stores the first file's summaries during its provider call and the second file then hits a busy writer:writer_busywithmutation_performed: false,summaries_committed: 0,chunks_summarized: 0, no note, only the other writer's row stored, schema-valid.mutation_performed: false, schema-valid.Added in the sixth review round (per-call tally):
summarize_file_chunkscalls on one writer, where only one commits, with the interleaving asserted: the committing call reportssummaries_committed: 1, the other0.summarize_samplecarries nosummaries_committed, top level or per file.Results at bc1ff4e:
tests/test_issue_145_serve_during_rebuild.py: 45 tests, all passed.summarization.pyand onesummarize_sampleresponse field.Results at 05c1cc4:
lock_registryorSummaryGenerationResult): 1871 passed, 5 skipped, 0 failed.tests/test_issue_145_serve_during_rebuild.py: 44 tests, all passed.Results at b574cac:
Earlier results at 4ae09f8 (rebased onto origin/main
9f956e4):repository summarize, tasks, stdio and schema contracts, handlers, client, readiness, git index manager, watcher sweep and reconciliation): 1832 passed, 5 skipped, 4 failed. The 4 failures were intest_mcp_server_cli.py, whose fake readiness lacksqueryable; fixed with thereadyfallback, and those files then passed (84 tests).blackandruffpass on the changed files.test_v13_data_reconciliation.pynow passes on the rebased base, after fix(sync): watcher sweep reconciles a new committed change again (#163) #164.Docs
docs/SUPPORT_MATRIX.md: readiness paragraph, state table, write fencing and the single observation per query.README.mdanddocs/operations/deployment-runbook.md: a note on the rebuild exception.Refs #145
🤖 Generated with Claude Code